﻿using Romantics.Domain;
using Romantics.Domain.Objects;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Romantics.Controllers
{
    public class HomeController : Controller
    {
        private readonly IDomainRepository _domainRepository;

        public HomeController(IDomainRepository domainRepository)
        {
            _domainRepository = domainRepository;
        }

        public ViewResult Index()
        {
            Options options = _domainRepository.Options();
            return View(options);
        }

        public ViewResult Contact()
        {
            return View();
        }

        [HttpPost]
        public ViewResult Contact(Contact contact)
        {
            if (ModelState.IsValid)
            {
                Options options = _domainRepository.Options();
                using (var client = new SmtpClient(options.SMPT_Server, options.SMPT_Port))
                {
                    var from = new MailAddress(options.AdminEmail, String.Format("Посетитель {0}", contact.Name));
                    var to = new MailAddress(options.AdminEmail, "Администратор");
                    client.Credentials = new System.Net.NetworkCredential(
                          options.SMPT_UserName
                        , options.SMPT_Password
                        );
                    using (var message = new MailMessage(from, to))
                    {
                        message.Body = contact.Body;
                        message.IsBodyHtml = true;
                        message.BodyEncoding = Encoding.UTF8;

                        message.Subject = contact.Subject;
                        message.SubjectEncoding = Encoding.UTF8;

                        message.ReplyToList.Add(new MailAddress(contact.Email, contact.Name));

                        client.Send(message);
                    }
                }

                return View("Thanks");
            }

            return View();
        }

        [ChildActionOnly]
        public PartialViewResult Contacts()
        {
            Options options = _domainRepository.Options();
            return PartialView("_Contacts", options);
        }
    }
}
